<?php

namespace App\Models\Home;

use function Couchbase\defaultDecoder;
use Illuminate\Database\Eloquent\Model;
use Spatie\Permission\Traits\HasRoles;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use Frame;
use Part;

class Users extends Model
{
    use HasRoles;

    protected $guard_name = 'web';
    protected $table = 'users';
    protected $guarded = [];
    protected $hidden = ['password'];

    public function frame()
    {
        return $this->belongsTo('App\Models\Home\Frame','frame_id','id');
    }

    public function mac_user()
    {
        return $this->belongsTo('App\Models\Home\Users','mac_uid','id');
    }

    public function download_log()
    {
        return $this->hasMany('App\Models\Home\DownloadLog','uid','id');
    }

    public function login_log_one()
    {
        return $this->hasOne('App\Models\Home\LoginLog','uid','id');
    }

    public function login_log_all()
    {
        return $this->hasMany('App\Models\Home\LoginLog','uid','id');
    }

    public function getMacList()
    {
        return self::where('status',1)->whereNotNull('mac')->get()->load('mac_user');
    }

    public function getNoMacList()
    {
        return self::where('status',1)->whereNull('mac')->get();
    }

    public function client()
    {
        return $this->hasMany('App\Models\Home\Client', 'assign', 'id');
    }

    public function position()
    {
        return $this->hasMany('App\Models\Home\Position', 'assign', 'id');
    }

    public function resume()
    {
        return $this->hasMany('App\Models\Home\Resume', 'assign', 'id');
    }

    public function deliver()
    {
        return $this->hasMany('App\Models\Home\Deliver', 'assign', 'id');
    }

    public function schedule()
    {
        return $this->hasMany('App\Models\Home\DeliverSchedule', 'assign', 'id');
    }

    public function finance()
    {
        return $this->hasMany('App\Models\Home\Finance', 'assign', 'id');
    }

    public function up_salary()
    {
        return $this->hasMany('App\Models\Home\UpSalary', 'assign', 'id');
    }

    public function getList($opt=array(),$order=array(),$in=array()){

        if (!empty($order) && count($order) == 2){

            $query = self::Orderby($order[0],$order[1]);

        }else{

            $query = self::Orderby('id','desc');

        }


        if (!empty($opt)){
            foreach ($opt as $k => $v){
                if(is_array($v) && $v[1]){
                    $query = $query->where($k,$v[0],$v[1]);
                }elseif(!is_array($v) && $v !== false){
                    $query = $query->where($k,$v);
                }
            }
        }

        if (!empty($in) && count($in)==2){
            $query = $query->whereIn($in[0],$in[1]);
        }

        $list = $query->where('status',1)->get();

        foreach ($list as $k => $v){
            switch ($v->sex){
                case 1:
                    $sex_name = '男';
                    break;
                case 2:
                    $sex_name = '女';
                    break;
                default:
                    $sex_name = '';
            }

            switch ($v->education){
                case 1:
                    $education_name = '大专';
                    break;
                case 2:
                    $education_name = '本科';
                    break;
                case 3:
                    $education_name = '硕士';
                    break;
                case 4:
                    $education_name = '博士';
                    break;
                default:
                    $education_name = '';
            }

            $list[$k]->sex_name = $sex_name;
            $list[$k]->education_name = $education_name;
        }

        return $list;

    }

    public function getUserList($opt=array(),$in=array()){

        $query = self::where('status',1);

        if (!empty($opt)){
            foreach ($opt as $k => $v){
                if(is_array($v) && $v[1]){
                    $query = $query->where($k,$v[0],$v[1]);
                }elseif(!is_array($v) && $v !== false){
                    $query = $query->where($k,$v);
                }
            }
        }

        if (!empty($in) && count($in)==2){
            $query = $query->whereIn($in[0],$in[1]);
        }

        $list = $query->get();

        return $list;
    }

    public function getResultCount($result,$member_user,$between){
        $member_user->load(['schedule'=> function ($query) use($between,$result){
            $query->whereBetween('created_at', $between)->where('result',$result);
        }]);

        $result_count = 0;
        foreach ($member_user as $key => $item){
            $result_count += count($item->schedule);
            unset($item->schedule);
        }

        return $result_count;

    }

    public function getClientCount($member_user,$between){
        $member_user->load(['client'=>function($query) use($between){
            $query->whereBetween('created_at', $between)->where('status','!=','-1');
        }]);

        $client_count = 0;
        foreach ($member_user as $key => $item){
            $client_count += count($item->client);
            unset($item->client);
        }

        return $client_count;


    }

    public function getPositionCount($member_user,$between){
        $member_user->load(['position'=>function($query) use($between){
            $query->whereBetween('created_at', $between)->where('status','!=','-1');
        }]);

        $position_count = 0;
        foreach ($member_user as $key => $item){
            $position_count += count($item->position);
            unset($item->position);
        }

        return $position_count;


    }

    public function getResumeCount($member_user,$between){
        $member_user->load(['resume'=>function($query) use($between){
            $query->whereBetween('created_at', $between)->where('status','!=','-1');
        }]);

        $resume_count = 0;
        foreach ($member_user as $key => $item){
            $resume_count += count($item->resume);
            unset($item->resume);
        }

        return $resume_count;


    }

    public function getFinanceCount($member_user,$between){
        $member_user->load(['finance'=>function($query) use($between){
            $query->whereBetween('created_at', $between);
        }]);

        $receipts = 0;
        foreach ($member_user as $key => $item){
            if(count($item->finance)){
                foreach ($item->finance as $val){
                    $one = intval($val->one_receipts);
                    $tow = intval($val->two_receipts);
                    $receipts += $one+$tow;
                }
            }
            unset($item->finance);
        }

        return $receipts;


    }

    public function getSelfDeliverCount($user=null,$between=null,$result=array()){
        if (is_null($user) || is_null($between) || empty($between) || empty($result)){
            return [];
        }

        $user->load('frame');
        $frame_id = $user->frame?$user->frame->id:0;
        $member = Frame::getMember($frame_id);
        $member[] = Auth::id();
        $member = array_merge($member,Part::getPartUser($member));

        $member_user = Users::where('status',1)->whereIn('id',$member)->get();

        $data = [];
        foreach ($result as $item){
            $resume_count_name = $item.'count';
            $data[$resume_count_name] = $this->getResultCount($item,$member_user,$between);
        }

        $data['client_count'] = $this->getClientCount($member_user,$between);
        $data['position_count'] = $this->getPositionCount($member_user,$between);
        $data['resume_count'] = $this->getResumeCount($member_user,$between);
        $data['receipts'] = $this->getFinanceCount($member_user,$between);

        return $data;

    }

    public function getDeliverCount($between=null,$opt=array(),$result=array()){
        if (is_null($between) || empty($between)){
            $startOfMonth = Carbon::now()->startOfMonth();
            $endOfMonth = Carbon::now()->endOfMonth();
            $between = [$startOfMonth,$endOfMonth];
        }
        if (empty($result)){
            $result = [3];
        }

        $query = self::where('status',1)->where('type',1)->with(['frame.belong_user','deliver'=> function ($query) use($between,$result){
            $query->whereBetween('created_at', $between);
        },'schedule'=> function ($query) use($between,$result){
            $query->whereBetween('created_at', $between)->whereIn('result',$result);
        }]);

        $query->withCount(['resume as resume_count'=>function($query) use($between){
            $query->whereBetween('created_at', $between);
        }]);
        $query->with(['position'=>function($query) use($between){
            $query->whereBetween('created_at', $between);
        }]);

        if (!empty($opt)){
            foreach ($opt as $k => $v){
                if(is_array($v) && $v[1]){
                    $query = $query->where($k,$v[0],$v[1]);
                }elseif(!is_array($v) && $v !== false){
                    $query = $query->where($k,$v);
                }
            }
        }

        $list = $query->get();

        foreach ($list as $key => $val){

            $list[$key]->team_name = $val->frame?$val->frame->belong_user?$val->frame->belong_user->username:'':'';

            $list[$key]->cv = $this->getCV($val);

            $result_Count = $this->getScheduleCount($val,$result);

            foreach ($result_Count as $name => $count){

                $list[$key]->$name = $count;

            }

            $list[$key]->hc = 0;

            if (count($val->position)){

                foreach ($val->position as $k => $v){

                    $list[$key]->hc = $list[$key]->hc + intval($v->hc);

                }

            }

            unset($list[$key]->position);
            unset($list[$key]->deliver);
            unset($list[$key]->frame);
        }

        return $list;

    }

    public function getCV($user=null){
        if (is_null($user)){
            return 0;
        }

        $cv = 0;

        if (count($user->deliver)){

            $deliver = $user->deliver->groupBy('resume_id');

            $cv = count($deliver);

        }

        return $cv;

    }

    public function getScheduleCount($user=null,$result){
        $return = [];

        foreach($result as $item){

            $name = $item.'count';

            $return[$name] = 0;

        }

        if (is_null($user)){
            return $return;
        }

        if (count($user->schedule)){

            $schedule = $user->schedule->groupBy('result');

            if (count($schedule)){

                foreach($result as $item){

                    if (isset($schedule[$item])){

                        $name = $item.'count';

                        $return[$name] = count($schedule[$item]->groupBy('deliver_id'));

                    }

                }

            }

        }

        return $return;

    }

    public function getUserRI($uid=null){
        if (is_null($uid)){
            return [];
        }

        $query = self::where('id',$uid);

        $query->withCount('login_log_all as login_count');

        $query->with(['frame.branch','login_log_one'=>function($query){
            $query->orderBy('id','desc');
        }]);

        $user = $query->first();

        $user->branch_name = $user->frame?$user->frame->branch?$user->frame->branch->name:'':'';

        $user->last_login_ip = $user->login_log_one?$user->login_log_one->ip:'';

        if ($user->last_login_ip){
            $ip_res = @file_get_contents("http://ip.taobao.com/service/getIpInfo.php?ip=".$user->last_login_ip);
            $ip_data = json_decode($ip_res,true);
            if ($ip_data && $ip_data['code'] == 0){
                if($ip_data['data']['isp_id'] == 'local'){
                    $user->last_login_address = $user->last_login_ip;
                }else{
                    $user->last_login_address = $ip_data['data']['country'].$ip_data['data']['area'].$ip_data['data']['region'].$ip_data['data']['city'];
                }
            }else{
                $user->last_login_address = $user->last_login_ip;
            }
        }

        $user->last_login_time = $user->login_log_one?$user->login_log_one->created_at:'';

        return $user;
    }


}
